package com.awenhui.demo.demo.thread;

import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * 阻塞队列实现生产者消费者模式
 *
 * @author yuxf
 * @version 1.0
 * @date 2021/7/2 9:49
 */
public class ProductorAndCustomer1 {

    static BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(3);
    static  boolean flag=false;

    public static void main(String[] args) {
        //一个生产者不停的往里面放入
        new Thread(new Productor1(blockingQueue)).start();


        //多个消费者消费
        for (int i = 0; i < 3; i++) {
            new Thread(new Customer1(blockingQueue), "Consumer" + (i + 1)).start();
        }
    }
}

/**
 * 生产者
 */
class Productor1 implements Runnable {

    BlockingQueue<String> blockingQueue;

    public Productor1(BlockingQueue<String> blockingQueue) {
        this.blockingQueue = blockingQueue;
    }

    @Override
    public void run() {
        while (true) {
            String product = "产品-" + Thread.currentThread().getName() + UUID.randomUUID();
            System.out.println("" + product + "等待进入队列");
            try {
                blockingQueue.put(product);
                System.out.println(product + "进入队列");
                Thread.sleep(3000);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

    }
}

/**
 * 消费者
 */
class Customer1 implements Runnable {

    BlockingQueue<String> blockingQueue;

    public Customer1(BlockingQueue<String> blockingQueue) {
        this.blockingQueue = blockingQueue;
    }

    @Override
    public void run() {
        while (true) {
            System.out.println("消费者【"+Thread.currentThread().getName()+"】等待消费产品");
            try {

                String product = blockingQueue.take();
                System.out.println("消费者【"+Thread.currentThread().getName()+"】消费" + product);
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
